package com.uni.dao;

import com.uni.entity.Order;
import com.uni.service.Service;
import com.uni.utils.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * --------------project-------------
 *
 * @Author Unirithe  - Mr.Chao
 * - CSDN:
 * https://blog.csdn.net/Unirithe
 * - GitHub:
 * https://github.com/unirithe
 * @create 2021/12/24 11:24
 * ------------------------------------------
 */
public class OrderDaoImpl implements OrderDao{

    @Override
    public boolean insertOrder(int uid, int cid) {
        Connection connection = DruidUtil.getConnection();
        String sql = "insert into commodity_order (uid, cid, status) values(?, ?, ?)";
        boolean ok = false;
        try{
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, uid);
            pstmt.setInt(2, cid);
            pstmt.setInt(3, 1);
            ok = pstmt.execute();
            DruidUtil.release(connection, pstmt, null);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return ok;
    }

    @Override
    public boolean deleteOrder(int uid, int cid) {
        Connection connection = DruidUtil.getConnection();
        String sql = "delete from commodity_order where uid = ? and cid = ?";
        boolean ok = false;
        try{
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, uid);
            pstmt.setInt(2, cid);
            ok = pstmt.execute();
            DruidUtil.release(connection, pstmt, null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ok;
    }

    @Override
    public List<Order> queryAllByUid(int uid) {
        List<Order> list = new ArrayList<>();
        Connection connection = DruidUtil.getConnection();
        String sql = "select * from commodity_order where uid = ?";
        boolean ok = false;
        try{
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, uid);
            ResultSet rs = pstmt.executeQuery();
            while(rs.next())
                list.add(new Order(rs.getInt(1),
                        Service.user.queryUserById(rs.getInt(2)),
                        Service.commodity.query(rs.getInt(3)),
                        rs.getInt(4),
                        rs.getTimestamp(5)));

            DruidUtil.release(connection, pstmt, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
